# -*- coding: utf-8 -*-

"""
Date: 2023/2/23 16:27
Author: Darker
"""
import pathlib
import pickle
from typing import Dict, NoReturn, Any, Text, Union, List, Optional
import re


def dump(filePath: Text, configData: Dict) -> NoReturn:
    """
    序列化内容到指定文件
    :param filePath: 文件路径
    :param configData: 待序列化的内容
    :return:
    """
    pathlib.Path(filePath).parent.mkdir(parents=True, exist_ok=True)
    with open(filePath, "wb") as fileWriter:
        pickle.dump(configData, fileWriter)


def load(filePath: Text) -> Any:
    """
    反序列化文件中的内容
    """
    with open(filePath, "rb") as fileReader:
        return pickle.load(fileReader)


def get_value_from_json(obj: Union[Dict, List], key: Text) -> Any:
    """
    从dictObj对象中获取key所对应的值
    :param obj: 待查找的对象
    :param key: 关键字key
    :return: Any
    """
    ret = []

    def _get_value_from_json(_obj):
        if isinstance(_obj, list):
            for obj_ in _obj:
                _get_value_from_json(obj_)
        elif isinstance(_obj, Dict):
            for key_, value_ in _obj.items():
                if key_ == key:
                    ret.append(value_)
                else:
                    if isinstance(value_, (Dict, List)):
                        _get_value_from_json(value_)
    _get_value_from_json(obj)
    return ret


def trans_str_to_list(data: Optional[Any]) -> Union[Any, List[Optional[Any]]]:
    """
    将data转换为[data],如果data为空则返回空列表
    :param data: 待转换的字符串
    :return:
    """
    data = data or []
    if isinstance(data, Text):
        data = [data]
    return data


def search_result(oldList: List, filterStr: Text) -> List:
    """
    根据filterStr筛选列表各项，返回包含filterStr项组成的新列表
    :param oldList: 原列表
    :param filterStr: 过滤字段
    :return: 筛选后的新列表
    """
    if not filterStr:
        return oldList
    return list(filter(lambda x: re.search(filterStr, x), oldList))


if __name__ == '__main__':
    a = [{"aa": 123, "bb": 123123}, {"aa": 123, "bb": 123123}]
    r = get_value_from_json(a, "bb")
    print(r)
